<template>
  <div class="voice-preview-container">
    <!-- 音频播放器 -->
    <audio ref="audioPlayerRef" controls :style="audioPlayerStyle" @ended="onAudioEnded" @error="onAudioError">
      您的浏览器不支持音频播放。
    </audio>

    <!-- 操作按钮组 -->
    <div class="voice-actions" v-if="showActions">
      <slot name="actions" :voiceActions="voiceActions">
        <!-- 默认按钮组 -->
        <a-button @click="handlePreview" :loading="isLoading" class="action-button">
          {{ isPlaying ? '停止' : '试听' }}
        </a-button>

        <a-button @click="handleDownload" :disabled="!audioUrl" class="action-button">
          下载
        </a-button>
      </slot>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useVoicePreview } from './useVoicePreview'

// 组件属性
const props = defineProps({
  // 要转换的文本内容
  text: {
    type: String,
    default: ''
  },
  // 音色类型
  voiceType: {
    type: String,
    default: 'male'
  },
  // 是否显示操作按钮
  showActions: {
    type: Boolean,
    default: true
  },
  // 音频播放器样式
  audioPlayerStyle: {
    type: Object,
    default: () => ({
      width: '100%',
      marginTop: '10px',
      display: 'none'
    })
  },
  // 下载文件名
  downloadFilename: {
    type: String,
    default: 'voice.wav'
  }
})

// 组件事件
const emit = defineEmits([
  'play-start',
  'play-end',
  'play-error',
  'download-start',
  'download-complete'
])

// 使用试听功能组合式API
const {
  audioPlayer,
  isPlaying,
  audioUrl,
  isLoading,
  initAudioPlayer,
  togglePlayback,
  stopPlayback,
  resetPlaybackState,
  onAudioEnded: handleAudioEnded,
  onAudioError: handleAudioError,
  downloadCurrentAudio
} = useVoicePreview()

// 音频播放器DOM引用
const audioPlayerRef = ref(null)

// 初始化音频播放器
onMounted(() => {
  if (audioPlayerRef.value) {
    initAudioPlayer(audioPlayerRef.value)
  }
})

// 清理资源
onUnmounted(() => {
  resetPlaybackState()
})

// 监听文本变化，自动重置播放状态
watch(() => props.text, () => {
  resetPlaybackState()
})

// 监听音色类型变化，自动重置播放状态
watch(() => props.voiceType, () => {
  resetPlaybackState()
})

// 处理试听按钮点击
const handlePreview = async () => {
  try {
    if (isPlaying.value) {
      emit('play-end')
    } else {
      emit('play-start')
    }

    await togglePlayback(props.text, props.voiceType)
  } catch (error) {
    emit('play-error', error)
  }
}

// 处理下载按钮点击
const handleDownload = async () => {
  try {
    emit('download-start')
    await downloadCurrentAudio(props.downloadFilename)
    emit('download-complete')
  } catch (error) {
    console.error('下载失败:', error)
  }
}

// 音频播放结束处理
const onAudioEnded = () => {
  handleAudioEnded()
  emit('play-end')
}
// 音频播放错误处理
const onAudioError = (error) => {
  handleAudioError(error)
  emit('play-error', error)
}

// 暴露给父组件的方法
const voiceActions = {
  play: () => handlePreview(),
  stop: () => stopPlayback(),
  download: () => handleDownload(),
  reset: () => resetPlaybackState()
}

// 暴露给父组件
defineExpose({
  ...voiceActions,
  isPlaying,
  isLoading,
  audioUrl
})
</script>

<style scoped>
.voice-preview-container {
  width: 100%;
}

.voice-actions {
  display: flex;
  gap: 8px;
  margin-top: 10px;
}

.action-button {
  flex: 1;
  min-width: 80px;
}

.action-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>